<template>
  <div class="create_form_box">
    <a-form :form="form">
      <!--      <a-form-item v-bind="formItemLayout" label="试验名称" class="form_style">-->
      <!--        <a-select-->
      <!--          v-decorator="[-->
      <!--            'select',-->
      <!--            { rules: [{ required: true, message: '请选择试验名称!' }] },-->
      <!--          ]"-->
      <!--          placeholder="请选择">-->
      <!--          <a-select-option value="china">-->
      <!--            China-->
      <!--          </a-select-option>-->
      <!--          <a-select-option value="usa">-->
      <!--            U.S.A-->
      <!--          </a-select-option>-->
      <!--        </a-select>-->
      <!--      </a-form-item>-->
      <a-form-item label="通知标题">
        <a-input v-decorator="['headline', { rules: [{ required: true, message: '请输入通知标题!' }] }]" placeholder="请输入（最大字数限制50字）" />
      </a-form-item>
      <a-form-item label="通知内容">
        <!--        <span slot="label">-->
        <!--          通知内容-->
        <!-- <a-tooltip placement="top">
            <template slot="title">
              <span>APP中展示信息</span>
            </template>
            <a-icon type="exclamation" class="tooltip_style" />
          </a-tooltip> -->
        <!--        </span>-->
        <a-textarea
          :rows="3"
          v-decorator="['content', {rules: [{required: true, message: '请输入通知内容!' }]}]"
          placeholder="请输入（最大字数限制200字）"/>
      </a-form-item>

      <div style="margin-bottom: 24px;">
        <a-radio-group @change="onChangeType" v-model="messageType">
          <a-radio :value="1">立即发送</a-radio>
          <a-radio :value="2">安排日期/时间</a-radio>
        </a-radio-group>
      </div>

      <a-form-item v-if="messageType===2" label="选择日期和时间">
        <a-date-picker @change="onChangeDate" v-decorator="['sendDate', { rules: [{ required: true, message: '请选择日期!' }] }]" placeholder="请选择日期" class="createForm_count_time" />
        &nbsp;
        <a-time-picker @change="onChangeTime" v-decorator="['sendTime', { rules: [{ required: true, message: '请选择时间!' }] }]" placeholder="请选择时间" class="createForm_count_time" />
      </a-form-item>

      <a-form-item label="目标用户">
        <!--        <a-input  v-decorator="['headline', { rules: [{ required: true, message: '请输入通知标题!' }] }]" placeholder="请输入（最大字数限制50字）" />-->
        <!--      <div style="margin-bottom: 24px;">-->
        <!--        <p class="create_form_item1_title"><span>*</span>目标用户</p>-->
        <a-radio-group v-decorator="['messageSendType', { rules: [{ required: true, message: '请选择目标用户！' }] }]" @change="onChangeSendType" v-model="messageSendType">
          <a-radio :value="1">全部用户</a-radio>
          <a-radio :value="2">分组用户</a-radio>
          <a-radio :value="3">特定用户</a-radio>
        </a-radio-group>
        <!--      </div>-->
      </a-form-item>
      <a-form-item v-if="messageSendType===2">
        <div v-for="(item, index) in informGroupDTOS" :key="index" :value="item">
          <a-select
            style="width:200px"
            v-model="item.experimentId"
            placeholder="请选择试验名称">
            <a-select-option v-for="item in experiments" :key="item.id" :value="item.id">
              {{ item.name }}
            </a-select-option>
          </a-select>
          <a-select
            style="margin-left: 20px; width:300px"
            v-model="item.userStatus"
            defau
            placeholder="请选择用户状态">
            <a-select-option value="1">未开启</a-select-option>
            <a-select-option value="2">进行中</a-select-option>
            <a-select-option value="3">完成</a-select-option>
            <a-select-option value="4">退出(主动退出) </a-select-option>
            <a-select-option value="5">不合格（后台管理员操作退出）</a-select-option>
          </a-select>
          <div style=" display: inline-block;position: relative; " >
            <div class="icon_delete" v-if="informGroupDTOS.length!==1" @click="informGroupDTOSDelete(index)">
              <a-icon type="delete" :style="{ fontSize: '15px', color: '#FFFFFF',margin:'0 auto' }" />
            </div>
            <div class="icon_add" v-if="informGroupDTOS.length === index+1" @click="informGroupDTOSAdd(index)">
              <a-icon type="plus-circle" :style="{ fontSize: '15px', color: '#FFFFFF',margin:'0 auto' }" />
            </div>
          </div>
        </div>
      </a-form-item>

      <a-form-item v-if="messageSendType===3">
        <a-select v-if="!userIdLoading" mode="multiple" v-decorator="['selectedUserIds', { rules: [{ required: true, message: '请选择用户编号！' }] }]" placeholder="请选择用户编号">
          <a-select-option v-for="item in userIds" :key="item.id" :value="item.id">
            {{ item.userName }}
          </a-select-option>
        </a-select>
        <div v-if="userIdLoading">
          <a-spin />
        </div>
      </a-form-item>

    </a-form>

    <div class="create_form_font">
      <a-button size="large" key="cancel" @click="handleCancel" style="margin-left:20px;">取消</a-button>
      <a-button
        size="large"
        key="forward"
        :loading="confirmLoading"
        type="primary"
        @click="handleAdd()"
        style="margin-left:20px;">提交</a-button>
    </div>

  </div>

</template>

<script>
import { postMessageAdd, getUserNameList, getUserSetListOf } from '@/api/manage'

export default {
  name: 'NotificationForm',
  data () {
    return {
      userIds: [],
      experiments: [],
      confirmLoading: false,
      userIdLoading: false,
      messageType: 1,
      messageSendType: 1,
      // sendDate: '',
      // selectedUserIds: [],
      // sendTime: '',
      informGroupDTOS: [{
        'experimentId': '请选择试验名称',
        'userStatus': '请选择用户状态'
      }],
      form: this.$form.createForm(this)
    }
  },
  created () {
    setTimeout(() => {
      this.form.setFieldsValue({ messageSendType: 1 })
    }, 100)
    this.getUserNameList()
    this.getExperimentList()
  },
  methods: {
    getUserNameList () {
      getUserNameList().then(res => {
        console.log(res.message)
        this.userIds = res.data
        // return res.data
      })
    },
    getExperimentList () {
      getUserSetListOf().then(res => {
        console.log(res.message)
        this.experiments = res.data
        // return res.data
      })
    },
    // 每日任务添加
    informGroupDTOSAdd (v) {
      this.informGroupDTOS.push({
        'experimentId': '请选择试验名称',
        'userStatus': '请选择用户状态'
      })
    },
    //  每日任务删除
    informGroupDTOSDelete (v) {
      this.informGroupDTOS.splice(v, 1)
    },
    handleCancel () {
      this.$emit('Cancel')
    },
    handleAdd () {
      // eslint-disable-next-line handle-callback-err
      this.form.validateFields((err, values) => {
        console.log(values)
        // debugger

        if (!values) {
          return
        }

        if (!values['headline'] || !values['content'] || !values['messageSendType']) {
          return
        }

        const headline = values['headline']
        const content = values['content']
        const messageSendType = values['messageSendType']
        let sendDate = ''
        let sendTime = ''
        let selectedUserIds = []
        const informGroupDTOS = []
        try {
          if (this.informGroupDTOS && this.informGroupDTOS.length > 0) {
            for (const group in this.informGroupDTOS) {
              if (this.informGroupDTOS[group].experimentId &&
                this.informGroupDTOS[group].experimentId !== '请选择试验名称' &&
                this.informGroupDTOS[group].userStatus &&
                this.informGroupDTOS[group].userStatus !== '请选择用户状态') {
                informGroupDTOS.push(this.informGroupDTOS[group])
              }
            }
          }

          if (values['selectedUserIds']) {
            selectedUserIds = values['selectedUserIds']
          }

          if (values['sendDate']) {
            sendDate = values['sendDate'].format('YYYY-MM-DD')
          }

          if (values['sendTime']) {
            sendTime = values['sendTime'].format('HH:mm:ss')
          }
        } catch (e) {
          console.log('loadData.param', e)
        }

        if (this.messageType === 2) {
          if (!sendDate || !sendTime) {
            this.$message.error('请选择日期和时间！')
            return
          }
        }

        if (this.messageSendType === 2) {
          if (!informGroupDTOS || informGroupDTOS.length <= 0) {
            this.$message.error('请选择试验名称及用户状态！')
            return
          }
        } else if (this.messageSendType === 3) {
          if (!selectedUserIds || selectedUserIds.length <= 0) {
            this.$message.error('请选择用户编号！')
            return
          }
        }

        const body = {
          headline: headline,
          content: content,
          type: this.messageType,
          sendDate: sendDate,
          sendTime: sendTime,
          sendType: messageSendType,
          informGroupDTOS: informGroupDTOS,
          userIds: selectedUserIds
        }

        // debugger
        this.confirmLoading = true
        postMessageAdd(body).then(res => {
          console.log(res.message)
          // this.roles = res.data
          // debugger
          // this.selectedRoles = res.data.roles
          // return res.data
          // this.createFormBox = true
          this.confirmLoading = false
          // this.$refs.table.refresh(true)
          // this.confirmLoading = false
          if (res.code === 200) {
            this.$message.success(res.message)
            // this.createFormEdit = false
            // this.$refs.table.refresh(true)
            this.createFormSuccess = true
            this.$emit('ok')
          } else {
            this.$message.error(res.message)
          }
          // this.$emit('ok')
        })
      })
    },
    onChangeTime () {
      // eslint-disable-next-line handle-callback-err
      this.form.validateFields((err, values) => {
        console.log(values)
      })
    },
    onChangeDate () {
      // eslint-disable-next-line handle-callback-err
      this.form.validateFields((err, values) => {
        console.log(values)
      })
    },
    onChangeType () {
      console.log(this.messageType)
    },
    onChangeSendType () {
      console.log(this.messageSendType)
    }
  }
}
</script>
<style lang="less" >
.icon_delete {
  cursor: pointer;
  display: inline-block;
  width: 32px;
  height: 32px;
  background: rgba(238, 114, 114, 1);
  box-shadow: 0px 2px 4px 0px rgba(255, 215, 215, 1);
  border-radius: 4px;
  text-align: center;
  line-height: 32px;
  margin-left: 20px;
}
.icon_add {
  cursor: pointer;
  display: inline-block;
  width: 32px;
  height: 32px;
  border-radius: 4px;
  text-align: center;
  line-height: 32px;
  background: rgba(86, 206, 209, 1);
  box-shadow: 0px 2px 4px 0px rgba(107, 203, 206, 0.68);
  border-radius: 4px;
  margin-left: 20px;
}
.create_form_box {
  margin: 24px 68px;
}
.create_form_font {
  float: right;
}

.create_form_item1_title {
  font-size: 16px;
  font-weight: 400;
  color: #000000;
  span {
    font-size: 17px;
    color: #d31e27;
  }
}

  .form_style{
    width: 224px;
  }
.createForm_count_time {
  min-width: 165px;
  margin-right: 20px;
}
</style>
